<template>
  <el-card>
    <h4 class="mb-20px">{{ id === -1 ? '新增' : '编辑' }}</h4>
    <el-row>
      <el-col :span="7">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="auto"
          v-loading="formLoading"
        >
          <el-form-item label="公司ID" prop="id">
            <el-input v-model="formData.id" placeholder="创建后自动生成" disabled />
          </el-form-item>
          <el-form-item label="公司名称" prop="corporateName">
            <el-input v-model="formData.corporateName" placeholder="请输入公司名称" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="formData.sort" type="number" min="0" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="上传图片" prop="imagePath">
            <UploadImg v-model="formData.imagePath" />
          </el-form-item>
        </el-form>
        <div>
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
          <el-button
            @click="
              () => {
                $router.back()
                delVisitedView(route)
              }
            "
            >取 消</el-button
          >
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import { AllianceMembersApi, AllianceMembers } from '@/api/biz/alliancemembers'
import { useTagsViewStore } from '@/store/modules/tagsView'

const { delVisitedView } = useTagsViewStore()
const route = useRoute()
const router = useRouter()

/** 联盟成员链接 表单 */
defineOptions({ name: 'AllianceMembersForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const id = +useRoute().params.id

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  corporateName: undefined,
  sort: undefined,
  visitors: undefined,
  status: 0,
  imagePath: undefined
})
const formRules = reactive({
  corporateName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  imagePath: [{ required: true, message: '图片地址不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AllianceMembersApi.getAllianceMembers(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AllianceMembers
    if (formType.value === 'create') {
      await AllianceMembersApi.createAllianceMembers(data)
      message.success(t('common.createSuccess'))
    } else {
      await AllianceMembersApi.updateAllianceMembers(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    router.back()
    delVisitedView(route)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    corporateName: undefined,
    sort: undefined,
    visitors: undefined,
    status: 0,
    imagePath: undefined
  }
  formRef.value?.resetFields()
}

open(id === -1 ? 'create' : 'update', id === -1 ? undefined : id)
</script>
